<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="区域" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="请选择区域">
          <el-option
            v-for="area in areaList"
            :key="area.areaId"
            :label="area.areaName"
            :value="area.areaId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="摘要" prop="subtitle">
        <el-input
          v-model="queryParams.subtitle"
          placeholder="请输入摘要"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="首页轮播" prop="hotFlag">
        <el-select v-model="queryParams.hotFlag" placeholder="请选择" clearable>
          <el-option label="" value=""> </el-option>
          <el-option label="是" value="1"> </el-option>
          <el-option label="否" value="0"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_news_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="推荐" prop="recommend" width="30px">
        <el-select v-model="queryParams.recommend" placeholder="请选择" clearable style="width:205px" >
          <el-option label="" value=""> </el-option>
          <el-option label="是" value="1"> </el-option>
          <el-option label="否" value="0"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="views">
        <el-select v-model="queryParams.type" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.sys_news_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:news:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:news:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:news:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:news:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :data="newsList"
              border
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
<!--      <el-table-column label="排序" align="center" prop="sort" width="60px"/>-->
      <el-table-column label="区域" align="center" prop="areaName" width="70px"/>
      <el-table-column label="标题" align="center" prop="title" width="530px"/>
<!--      <el-table-column label="摘要" align="center" prop="subtitle" width="400px"/>-->
      <el-table-column label="新闻类型" align="center" prop="typeName" width="90px"/>
      <el-table-column label="首页轮播" align="center" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.hotFlag"
            active-value="1"
            inactive-value="0"
            @change="handleHotFlagChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="推荐" align="center" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.recommend"
            active-value="1"
            inactive-value="0"
            @change="handleRecommendChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="浏览量" align="center" prop="views" width="60"/>
      <el-table-column label="状态" align="center" prop="status" width="60">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_news_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="发布人" align="center" prop="authorName" width="90px"/>
      <el-table-column label="发布时间" align="center" prop="publisherDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publisherDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:news:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:news:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改新闻对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" hight="900px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="区域" prop="areaId">
              <el-select v-model="form.areaId" placeholder="请选择">
                <el-option
                  v-for="area in areaList"
                  :key="area.areaId"
                  :label="area.areaName"
                  :value="area.areaId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="dict in dict.type.sys_news_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="首页轮播" prop="recommend">
              <el-radio-group v-model="form.hotFlag">
                <el-radio v-model="form.hotFlag" label="1">是 </el-radio>
                <el-radio v-model="form.hotFlag" label="0"> 否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="推荐" prop="recommend">
              <el-radio-group v-model="form.recommend">
                <el-radio v-model="form.recommend" label="1">是 </el-radio>
                <el-radio v-model="form.recommend" label="0"> 否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option
                  v-for="dict in dict.type.sys_news_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="摘要" prop="subtitle">
          <el-input v-model="form.subtitle" placeholder="请输入摘要" />
        </el-form-item>
        <el-form-item label="新闻主图">
          <image-upload v-model="form.image" :limit="1"/>
        </el-form-item>
        <el-form-item label="新闻内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布人" prop="author">
              <el-input v-model="form.authorName" placeholder="请输入发布人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="publisherDate">
              <el-date-picker clearable size="small"
                              v-model="form.publisherDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择发布时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listNews, getNews, delNews, addNews, updateNews, changeRecommend, changeHotFlag} from "@/api/system/news";
  import { listArea } from "@/api/system/area";
  import { getUserProfile } from "@/api/system/user";

export default {
  name: "News",
  dicts: ['sys_news_type', 'sys_news_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新闻表格数据
      newsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaId: null,
        title: null,
        subtitle: null,
        content: null,
        image: null,
        type: null,
        author: null,
        publisherDate: null,
        views: null,
        status: null,
      },
      // 表单参数
      form: {},
      areaList:[],
      user:{},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        subtitle: [
          { required: true, message: "小标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "新闻内容不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "新闻类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getAreaList();
    this.getUser();
  },
  methods: {
    /** 查询新闻列表 */
    getList() {
      this.loading = true;
      listNews(this.queryParams).then(response => {
        this.newsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询区域列表 */
    getAreaList() {
      this.loading = true;
      listArea(this.queryParams).then(response => {
        this.areaList = response.rows;
      });
    },

    getUser() {
      getUserProfile().then(response => {
        console.log("getUserProfile:" + JSON.stringify(response.data))
        this.user = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        newsId: null,
        areaId: null,
        areaName: null,
        title: null,
        subtitle: null,
        content: null,
        image: null,
        type: null,
        author: null,
        authorName: null,
        publisherDate: null,
        views: null,
        status: "0",
        delFlag: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        recommend: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.newsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //处理默认选中当前日期
    getNowTime() {
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var month = now.getMonth(); //得到月份
      var date = now.getDate(); //得到日期
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      var defaultDate = `${year}-${month}-${date}`;
      console.log(defaultDate)
      return defaultDate;
      this.$set(this.form, "stockDate", publisherDate);
    },

    //修改首页轮播
    handleHotFlagChange(row) {
      let text = row.recommend === "0" ? "取消" : "设置";
      this.$modal.confirm('确认要' + text + '【' + row.title + '】到首页轮播吗？').then(function() {
        return changeHotFlag({"newsId": row.newsId, "hotFlag": row.hotFlag});
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.hotFlag = row.hotFlag === "0" ? "1" : "0";
      });
    },
    // 新闻推荐修改
    handleRecommendChange(row) {
      let text = row.recommend === "0" ? "取消推荐" : "推荐";
      this.$modal.confirm('确认要' + text + '【' + row.title + '】到首页吗？').then(function() {
        return changeRecommend({"newsId": row.newsId, "recommend": row.recommend});
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.recommend = row.recommend === "0" ? "1" : "0";
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.publisherDate=this.getNowTime();
      this.form.author = this.user.userId;
      this.form.authorName = this.user.userName;
      this.open = true;
      this.title = "添加新闻";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const newsId = row.newsId || this.ids
      getNews(newsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改新闻";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.newsId != null) {
            updateNews(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNews(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const newsIds = row.newsId || this.ids;
      this.$modal.confirm('是否确认删除新闻编号为"' + newsIds + '"的数据项？').then(function() {
        return delNews(newsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/news/export', {
        ...this.queryParams
      }, `news_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
